package baseClass;

import baseAPI.Database;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

public class History {
    private String name;
    private int age;
    private String sex;
    private String idNumber;
    private int numberOfPeople;
    private int roomNumber;
    private String dateCheckIn;
    private String dateCheckOut;

    public History(String name, int age, String sex, String idNumber, int numberOfPeople, int roomNumber){
        this.name = name;
        this.age = age;
        this.sex = sex;
        this.idNumber = idNumber;
        this.numberOfPeople = numberOfPeople;
        this.roomNumber = roomNumber;
    }

    public void setDateCheckIn(String dateCheckIn){
        this.dateCheckIn = dateCheckIn;
    }

    public void setDateCheckOut(String dateCheckOut){
        this.dateCheckOut = dateCheckOut;
    }

    public void checkIn(Database database){
        database.insert("history", "\"" + name + "\"" + "," + age + "," + "\"" + sex + "\"" + "," + "\"" + idNumber + "\"" + "," + numberOfPeople +
                "," + "\"" + roomNumber + "\"" + "," + "localtime()" + "," + "null");
    }

    public static void checkOut(Database database, int roomNumber){
        database.update("history", "dateCheckOut", "localtime()", "roomNumber = " + "\"" + roomNumber + "\"" + " order by dateCheckIn desc limit 1");
    }

    public String[] getHistoryInformation(){
        return new String[]{name, String.valueOf(age), sex, idNumber, String.valueOf(numberOfPeople), String.valueOf(roomNumber), dateCheckIn, dateCheckOut};
    }

    public static ArrayList<History> getHistories(Database database){
        ResultSet resultSet = database.select("*", "history");
        return getHistory(resultSet);
    }

    public static ArrayList<History> getHistories(Database database, String where){
        ResultSet resultSet = database.select("*", "history", where);
        return getHistory(resultSet);
    }

    private static ArrayList<History> getHistory(ResultSet resultSet) {
        ArrayList<History> histories = new ArrayList<>();
        try{
            if(!resultSet.next()){
                return null;
            }
            else{
                do{
                    History history = new History(resultSet.getString(1), resultSet.getInt(2), resultSet.getString(3), resultSet.getString(4), resultSet.getInt(5), resultSet.getInt(6));
                    if(resultSet.getString(7) != null){
                        history.setDateCheckIn(resultSet.getString(7));
                    }

                    if(resultSet.getString(8) != null){
                        history.setDateCheckOut(resultSet.getString(8));
                    }
                    histories.add(history);
                }while(resultSet.next());
                return histories;
            }
        }catch (SQLException ex){
            System.out.println("getHistoriesException");
        }
        return null;
    }
}
